<script setup lang="ts">
import { uploadImage } from '@/services/consult'
import type { UploaderFileListItem } from 'vant'
import type { UploaderAfterRead } from 'vant/lib/uploader/types'
import { ref, watch } from 'vue'
import type { Image } from '@/types/consult'
import { baseURL } from '@/utils/request'

const modelValue = defineModel({ default: [] as any[] })


const props = defineProps({
  // 是否显示提示
  type: {
    type: String,
    default: ''
  },
});

const emit = defineEmits<{
  (e: 'update:modelValue', val: any): void
}>()

// 上传图片
const fileList = ref<Image[]>([])

watch(() => modelValue.value, val => {
  // 然后将数组转为对象数组
  fileList.value = val.map(item => {
    if (item.filePath.indexOf(baseURL) === -1) {
      return { url: baseURL + item.filePath };
    } else {
      return { url: item.filePath };
    }
  });
}, { deep: true, immediate: true });

// 图片上传
const onAfterRead: UploaderAfterRead = (item) => {
  if (Array.isArray(item)) return
  if (!item.file) return

  item.status = 'uploading'
  item.message = '上传中...'
  uploadImage(item.file)
    .then((res) => {
      item.status = 'done'
      item.message = undefined
      // item.url = res.filePath
      // 同步数据
      //   form.value.pictures?.push(res.data)
      // emit('uploadSuccess', res.filePath)

      fileList.value.push({ url: res.filePath })

      emit("update:modelValue", modelValue.value.concat({
        fileName: res.fileName,
        filePath: res.filePath,
        fileType: props.type
      }));
    })
    .catch(() => {
      // item.status = 'failed'
      item.message = '上传失败'
    })
}
const onDeleteImg = (item: UploaderFileListItem) => {
  let list = JSON.parse(JSON.stringify(modelValue.value))
  const findex = list.map(f => baseURL + f.filePath).indexOf(item.url);
  if (findex > -1) {
    list.splice(findex, 1);
    emit("update:modelValue", list);
    return false;
  }
}
</script>

<template>
  <div class="illness-img">
    <van-uploader upload-icon="photo-o" upload-text="上传图片" max-count="3" :max-size="10 * 1024 * 1024" v-model="fileList"
      :after-read="onAfterRead" @delete="onDeleteImg"></van-uploader>
    <p class="tip">
      上传最多3张图,最大10MB
    </p>
  </div>
</template>

<style scoped lang="scss">
.illness-img {
  padding-top: 16px;

  // margin-bottom: 40px;
  // display: flex;
  // align-items: center;
  .tip {
    font-size: 12px;
    color: var(--cp-tip);
  }

  ::v-deep() {
    .van-uploader {
      &__preview {
        &-delete {
          left: -6px;
          top: -6px;
          border-radius: 50%;
          background-color: var(--cp-primary);
          width: 20px;
          height: 20px;

          &-icon {
            transform: scale(0.9) translate(-22%, 22%);
          }
        }

        &-image {
          border-radius: 8px;
          overflow: hidden;
        }
      }

      &__upload {
        border-radius: 8px;
      }

      &__upload-icon {
        color: var(--cp-text3);
      }
    }
  }
}
</style>
